<template>
  <div style="width: 100%; height: 100%">
    <div ref="fullscreenDiv" class="real-video" :style="cMonitorVideoStyle">
      <!-- 左侧箭头 -->
      <div
        v-if="!LayoutStore.triggerScreen"
        class="devices-arrow"
        :style="cArrowLeftStyle"
        @click="showDevicesTree"
      >
        <span
          :class="[
            'iconfont',
            `icon-arrow-${devicesTreeVisible ? 'left' : 'right'}-s-fill`,
          ]"
        ></span>
      </div>
      <!-- 左侧设备列表 -->
      <div
        v-show="!LayoutStore.triggerScreen && devicesTreeVisible"
        class="devices"
      >
        <monitoring-center-card
          :ba-img="devicesBg"
          :header-bg="headerDeviceBg"
          title="摄像头列表"
        >
          <template #Content>
            <global-input-search
              v-model:value="searchValue"
              placeholder="关键字"
              style="
								width: calc(100% - 16px);
								margin-top: 16px;
								margin-left: 8px;
              "
              @focus="searchFocus"
            ></global-input-search>
            <devices-tree
              ref="refTree"
              v-if="showTree"
              v-model:selected-keys="selectedKeys"
              v-model:expanded-keys="expandedKeys"
              :search-value="searchValue"
              :tree-data="treeData"
              :video-plays="cVideoPlays"
              @select="TreeSelect"
              @expand="treeExpand"
            ></devices-tree>
          </template>
        </monitoring-center-card>
      </div>

      <!-- 中间视频部分 -->
      <div
        class="monitor-video-card monitor-video-center"
        :style="cVideoCenterStyle"
      >
        <div
          class="video-content-box"
          :style="{
            height: `calc(100% - ${LayoutStore.triggerScreen ? '0px' : '48px'})`,
            padding: LayoutStore.triggerScreen ? '0px' : '6px',
          }"
        >
          <div class="video-content-grid">
            <template
              :key="item?.id"
              v-for="(item, index) in currentConfig.deviceIds"
            >
              <monitoring-center-video
                :info="item"
                :is-show-ai-num="true"
                :is-open-region="recognizeRegionSwitch"
                :screen-type="currentConfig.screenType"
                :determine="
                  Array.isArray(currentConfig.determineList) &&
                  currentConfig.determineList[index]
                "
                @full="handleClickFullVideo"
                @close-video="closeVideo"
                @error="videoError"
              ></monitoring-center-video>
            </template>
            <div
              :key="item"
              v-for="item in emptyNums"
              :class="`video-item${currentConfig.screenType}`"
            >
              <div class="video-empty">
                <div class="empty-image">
                  <global-svg-icon
                    icon-name="camera-empty"
                    width="48px"
                    height="48px"
                  ></global-svg-icon>
                  <div class="empty-description">选择设备</div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 视频操作按钮 -->
        <div v-show="!LayoutStore.triggerScreen" class="video-top-bar">
          <ul>
            <li
              :key="item.screenNum"
              v-for="(item, index) in videoControlsList"
              :class="[
                currentConfig.screenType === item.value
                  ? 'screen-btn-active'
                  : '',
              ]"
            >
              <a-tooltip>
                <template #title>{{ `${item.screenNum}屏模式` }}</template>
                <global-svg-icon
                  class-name="video-control-icon"
                  :icon-name="item.iconName"
                  width="30px"
                  height="30px"
                  @click="handleClickChangeScreen(item.value)"
                ></global-svg-icon>
              </a-tooltip>
            </li>

            <div class="screen-all-btn">
              <div>
                <a-tooltip>
                  <template #title>全屏模式</template>
                  <global-svg-icon
                    style="margin-right: 12px"
                    class-name="video-control-icon"
                    icon-name="daping-fill"
                    width="30px"
                    height="30px"
                    @click="toggleFullscreen"
                  ></global-svg-icon>
                </a-tooltip>
              </div>

              <div>
                <a-tooltip>
                  <template #title>大屏模式</template>
                  <global-svg-icon
                    class-name="video-control-icon"
                    icon-name="fullscreen-line"
                    width="30px"
                    height="30px"
                    @click="toDashBoard"
                  ></global-svg-icon>
                </a-tooltip>
              </div>
            </div>
          </ul>
          <div class="discern-switch">
            <div>
              <a-switch
                v-model:checked="inspectionChecked"
                size="small"
                @click="inspectionCheckedBtn"
              ></a-switch
              ><span style="margin-right: 18px">智能巡检</span>
            </div>
            <div class="devices-btm">
              <a-switch
                v-model:checked="recognizeRegionSwitch"
                size="small"
                @change="rememberParma"
              ></a-switch
              ><span>识别区域</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧报警记录 -->
      <div v-show="screenFull" class="alarm-record">
        <monitoring-center-card title="报警记录" :header-bg="headerAlarmBg">
          <template #Header-Right>
            <div class="alarm-check">
              <a-checkbox
                v-model:checked="alarmChecked"
                @change="switchAlarmChecked"
              ></a-checkbox>
              <span>仅显示选中</span>
            </div>
          </template>
          <template #Content>
            <alarm-record
              ref="alarmBarRef"
              v-model:device-ids="deviceIds"
              @load-more="loadMore"
            ></alarm-record>
          </template>
        </monitoring-center-card>
      </div>

      <!-- 全屏按钮 -->
      <div
        id="screen-button"
        v-show="LayoutStore.triggerScreen && isHover"
        class="screen-button"
      >
        <a-tooltip
          placement="top"
          :get-popup-container="() => getPopupContainerEl"
        >
          <template #title>
            <span>视频和报警记录</span>
          </template>
          <div
            class="button-item"
            :class="[screenFull && 'active']"
            @click="handleClickFullView"
          >
            <span
              class="iconfont icon-fengpinHalf-line"
              style="color: #fff"
            ></span>
          </div>
        </a-tooltip>
        <a-tooltip
          placement="top"
          :get-popup-container="() => getPopupContainerEl"
        >
          <template #title>
            <span>仅视频</span>
          </template>
          <div
            class="button-item"
            :class="[!screenFull && 'active']"
            @click="handleClickVideoView"
          >
            <span
              class="iconfont icon-Fengpin1-1-line"
              style="color: #fff"
            ></span>
          </div>
        </a-tooltip>
        <div class="button-item-open">
          <div class="open-content" @click="closeFullscreen">
            <span
              class="iconfont icon-fullscreen-exit-line"
              style="color: #fff"
            ></span>
          </div>
        </div>
      </div>
    </div>

    <video-modal ref="videoModalRef"></video-modal>
    <inspection-data-permissions
      v-if="inspectionVisible"
      :screen="currentConfig.screenType"
      @ok="setTableData()"
      @close="closeModel"
    ></inspection-data-permissions>
  </div>
</template>

<script setup lang="ts" name="real-video">
import ScreenFullPlug from 'screenfull';
import { message } from 'ant-design-vue';
import { videoPlay } from '@/global-utils/viedeo.utils';
import { g6Debounce } from 'glasssix-utils-ts';
import { exceedAuthority } from '@/global-utils/base.utils';
import { appStore } from '@/global-store/index';
import devicesBg from '@/global-assets/imgs/devices-bg.png';
import headerAlarmBg from '@/global-assets/imgs/alarm-title.png';
import headerDeviceBg from '@/global-assets/imgs/devices-title.png';
import {
	TsCurrentConfigProps,
	TsDeviceIdsItem,
	TsPlayerQueue,
	TsSelectNode
} from '../../type';
import { realVideoApi } from '../../api';
import { findNodeByIndex } from '../../utils';
import {
	DevicesTree,
	AlarmRecord,
	MonitoringCenterCard,
	MonitoringCenterVideo,
	VideoModal,
	InspectionDataPermissions
} from '../../components/index';
import { useDeleteModal } from '@/global-hooks/base.hooks';

const { setOpenDeleteModal } = useDeleteModal();

const { LayoutStore } = appStore;
const router = useRouter();
const route = useRoute();
const recognizeRegionSwitch = ref<boolean>(false); // 识别区域开关
const inspectionChecked = ref<boolean>(false); // 智能巡检开关
const inspectionVisible = ref<boolean>(false); // 智能巡检开关
const selectedKeys = ref<(string | number)[]>([]); // 树选择
const expandedKeys = ref<(string | number)[]>([]); // 树展开
const rememberExpandedKeys = ref<(string | number)[]>([]); // 记忆展开
const searchValue = ref<string>(''); // 搜索值
const alarmChecked = ref<boolean>(false); // 报警是否显示选中切换

const token = window.sessionStorage.getItem('token');

const treeData = ref([]); // 树数据
const showTree = ref(false);
const refTree = ref();

/**
 * 获取默认配置
 */
const currentConfig = ref<TsCurrentConfigProps>({
	aiTagStatus: false,
	deviceIds: [], // 在播 列表数据
	id: 0,
	inspectionStatus: false,
	screenType: 1, // 屏幕数量
	userId: 0,
	determineList: [] // 是否高亮
});

// 记忆参数请求
const rememberParma = async (): Promise<void> => {
	let screenNum: number = currentConfig.value.screenType;

	let obj = {
		inspection: inspectionChecked.value ? 0 : 1, // 智能巡检
		identifyArea: recognizeRegionSwitch.value ? 0 : 1, // 识别区域
		screenNums: screenNum, // 屏幕数量
		playIds: currentConfig.value.deviceIds.map(
			(item: TsDeviceIdsItem) => item.id
		), // 播放列表
		openIds: searchValue.value.length
			? rememberExpandedKeys.value
			: expandedKeys.value, // 树展开
		deviceIds: currentConfig.value.deviceIds.map(
			(item: TsDeviceIdsItem) => item.areaOrDeviceId
		), // 当前播放的设备ids
		changeStatus: alarmChecked.value ? 1 : 0 // 报警列表状态
	};

	await realVideoApi.saveRemember(obj);
};

// ----------------------------------右侧列表的操作----------------------------------------------
const alarmBarRef = ref();
const deviceIds = ref<null | string>(null); // 报警记录列表ids
// 获取报警列表
const getAlarmList = async (): Promise<void> => {
	if (alarmChecked.value) {
		deviceIds.value = currentConfig.value.deviceIds
			.map((item: TsDeviceIdsItem) => item.areaOrDeviceId)
			.join(',');
	} else {
		deviceIds.value = null;
	}

	await alarmBarRef.value.getAlarmList(1, true, deviceIds.value);
};
// 报警记录切换
const switchAlarmChecked = async (): Promise<void> => {
	getAlarmList();
	rememberParma();
};

// 查看更多
const loadMore = (): void => {
	// 全部报警
	router.push('/alarms-center');
};

// ----------------------------------右侧列表的操作END-------------------------------------------

// ----------------------------------视频逻辑-------------------------------------------------

const playerQueue = ref<TsPlayerQueue[]>([]);
const videoModalRef = ref();
/**
 * 关闭视频
 * @param key  视频的id
 * @param isRemember  是否记忆 默认true记忆
 * @param inspection  是否开启智能巡检 默认不开启
 * @param areaOrDeviceId 关流接口
 */
const closeVideo = async (
	key: string,
	isRemember: boolean = true,
	inspection: boolean = false,
	areaOrDeviceId: number
	// eslint-disable-next-line max-params
): Promise<void> => {
	// 判断是否在智能巡检模式下
	// +++/更新/摄像头关流
	realVideoApi.getClose([areaOrDeviceId]);
	if (inspectionChecked.value && inspection) {
		const restartFun = async (): Promise<void> => {
			inspectionChecked.value = false;
			rememberParma();
		};
		const restartModalInfo = {
			title: '是否关闭智能巡检且关闭该摄像头画面？',
			okText: '确定',
			cancelText: '取消'
		};
		setOpenDeleteModal(restartFun, restartModalInfo);
		return;
	}

	// 智能巡检下 销毁实例
	if (inspectionChecked.value) {
		playerQueue.value
			.find((item: TsPlayerQueue) => item.key === key)
			?.play.close();
		return;
	}
	// 点播 关流
	playerQueue.value = playerQueue.value.filter((item: TsPlayerQueue) => {
		if (item.key === key) {
			if (item.play) {
				item.play.close();
				item.play = null as any;
			}
			//是否记忆
			currentConfig.value.deviceIds = currentConfig.value.deviceIds.filter(
				(item: TsDeviceIdsItem) => item.id !== key
			);
			if (isRemember) {
				!inspectionChecked.value && rememberParma();
				alarmChecked.value && getAlarmList();
			}
		}
		return item.key !== key;
	});
};

// 视频全屏弹窗
const handleClickFullVideo = (params: TsDeviceIdsItem): void => {
	videoModalRef.value?.openModal(params);
};

// 摄像头推流
const getVideoList = async (ids: any) => {
	// +++通过ids更新/摄像头推流
	await realVideoApi.getPlay(ids);
};
// 播放视频
const videoRender = async (
	videoParams: TsDeviceIdsItem,
	index: number
): Promise<void> => {
	videoParams.spinning = 0;
	videoPlay(
		{ videoDomId: `video${videoParams.id}`, videoUrl: videoParams.webrtc },
		(play: any, videoStatus: number) => {
			videoParams.spinning = videoStatus;
			if (!playerQueue.value[index]) {
				playerQueue.value[index] = { play, key: videoParams.id };
			}
		}
	);
};

// 视频报错
const videoError = (key: string): void => {
	let errorObj: any = playerQueue.value.find(
		(item: TsPlayerQueue) => item.key === key
	);
	errorObj &&
    errorObj.play &&
    errorObj.play.close() &&
    (errorObj.play = null) &&
    delete (
      currentConfig.value.deviceIds.find(
      	(item: TsDeviceIdsItem) => item.id === key
      ) as any
    )['id'];
};

// ----------------------------------视频逻辑END----------------------------------------------

// ----------------------------------左侧树的操作----------------------------------------------

const devicesTreeVisible = ref<boolean>(true); // 树可见？

const showDevicesTree = (): void => {
	devicesTreeVisible.value = !devicesTreeVisible.value;
};

const cArrowLeftStyle = computed(() => {
	let obj = {
		borderRadius: devicesTreeVisible.value ? '4px 0 0 4px' : '0 4px 4px 0',
		left: devicesTreeVisible.value ? '232px' : '0',
		color: '#fff'
	};
	return obj;
});

// 当前播放列表
const cVideoPlays = computed(() => {
	return currentConfig.value.deviceIds.map((item: TsDeviceIdsItem) => item.id);
});

// 树展开
const treeExpand = (): void => {
	if (!inspectionChecked.value) {
		rememberParma();
	}
};

// 搜索框 获取焦点 保存上次的展开
const searchFocus = (): void => {
	rememberExpandedKeys.value = [...expandedKeys.value];
};
const watchStop = watch(searchValue, (value) => {
	if (!value.length) {
		expandedKeys.value = [...rememberExpandedKeys.value];
	}
});

// 智能巡检
const inspectionCheckedBtn = (): void => {
	if (inspectionChecked.value) {
		inspectionVisible.value = true;
	}
	inspectionChecked.value = false;
};
// 点击树
const debounceRemember: any = g6Debounce(() => {
	rememberParma();
}, 1000);

// 判断是否在智能巡检模式下
const isInspectionChecked = () => {
	if (inspectionChecked.value) {
		const restartFun = async (): Promise<void> => {
			inspectionChecked.value = false;
			rememberParma();
		};
		const restartModalInfo = {
			title: '是否关闭智能巡检且查看该摄像头画面？',
			okText: '确定',
			cancelText: '取消'
		};
		setOpenDeleteModal(restartFun, restartModalInfo);
		return true;
	}
};
const TreeSelect = (node: TsSelectNode): void => {
	if (isInspectionChecked()) {
		return;
	}
	let nodeData = node as unknown as TsDeviceIdsItem;
	// 不是点击的设备 0区域 1设备
	if (nodeData.type !== 0) {
		return;
	}
	if (!nodeData.webrtc) {
		message.warning('该设备暂无视频');
		return;
	}
	const videoKey = nodeData.id;
	const isAlike = currentConfig.value.deviceIds.some(
		(videoKeys: TsDeviceIdsItem) => videoKeys.id === videoKey
	);

	// 如果找到相同的视频给关闭
	if (isAlike) {
		closeVideo(videoKey, true, false, node.areaOrDeviceId);
	} else {
		getVideoList([node.areaOrDeviceId]); //通过ids获取摄像头推流
		const currentVideo = currentConfig.value.deviceIds.length;
		const limitVideo = currentConfig.value.screenType;
		// 如果视频数量等于屏幕数量就替换最后一个
		if (currentVideo === limitVideo) {
			const popDevice = currentConfig.value.deviceIds.pop() as TsDeviceIdsItem;
			closeVideo(popDevice.id, true, false, node.areaOrDeviceId);

			currentConfig.value.deviceIds.push({ ...nodeData });
		} else {
			currentConfig.value.deviceIds.push({ ...nodeData });
		}
		const currentIndex = currentConfig.value.deviceIds.findIndex(
			(item: TsDeviceIdsItem) => item.id === videoKey
		);

		videoRender(
      currentConfig.value.deviceIds[currentIndex] as TsDeviceIdsItem,
      currentIndex
		);

		try {
			// rememberParma();
			debounceRemember();
			alarmChecked.value && getAlarmList();
		} catch (error) {
			console.log('error', error);
		}
	}
};
// // 根据disabled属性对children数组进行排序
const getDisabledSort = (data: any): void => {
	for (let i = 0; i < data.length; i++) {
		const node = data[i];

		if (node.children) {
			// node.children.forEach((item) => {
			// 	item.disabled = false;
			// });
			node.children.sort((a: any, b: any) =>
				a.disabled === b.disabled ? 0 : a.disabled ? 1 : -1
			);
			if (node.children) {
				getDisabledSort(node.children);
			}
		}
	}
};
const getTree = async (): Promise<void> => {
	try {
		let res: TsRes = await realVideoApi.tree();
		if (res) {
			treeData.value = res.data;
			showTree.value = true;
			getDisabledSort(treeData.value);
		}
	} catch (error) {
		console.log('error', error);
	}
};

// ----------------------------------左侧树的操作END-------------------------------------------

// --------------------------------屏幕操作---------------------------------------

const videoControlsList = [
	{ iconName: 'Fengpin1-fill', screenNum: '一', value: 1 },
	{ iconName: 'Fengpin4-fill', screenNum: '四', value: 4 },
	{ iconName: 'Fengpin9-fill', screenNum: '九', value: 9 }
];
const fullscreenDiv = ref<HTMLDivElement>();
const screenFull = ref<boolean>(true); // 全屏控制布局
const isHover = ref<boolean>(true);

// 全屏幕按钮
const toggleFullscreen = (): void => {
	const div = fullscreenDiv.value;
	screenFull.value = true;
	ScreenFullPlug.request(div);
};

// 退出全屏
const closeFullscreen = (): void => {
	screenFull.value = true;
	ScreenFullPlug.exit();
};

// 气泡框挂载
const getPopupContainerEl = ref<HTMLElement>(document.body);
// 全部显示
const handleClickFullView = (): void => {
	screenFull.value = true;
};

// 显示视频
const handleClickVideoView = (): void => {
	screenFull.value = false;
};

// 显示鼠标
const showMouse = (): void => {
	if (!fullscreenDiv.value) {
		return;
	}
	fullscreenDiv.value.style.cursor = 'default';
	isHover.value = true;
};

// 隐藏鼠标
const hideMouse = (): void => {
	if (!LayoutStore.triggerScreen) {
		return;
	}
	if (!fullscreenDiv.value) {
		return;
	}
	fullscreenDiv.value.style.cursor = 'none';
	isHover.value = false;
};

// 全屏状态下 控制悬浮气泡显隐藏
let timer: NodeJS.Timeout;
const watchEffectStop = watchEffect(() => {
	// 按键退出全屏 显示右侧报警列表
	if (!LayoutStore.triggerScreen) {
		screenFull.value = true;
	}
	const handleMouseMove = (): void => {
		clearTimeout(timer);
		showMouse();
		timer = setTimeout(hideMouse, 3000);
	};
	if (fullscreenDiv.value) {
		fullscreenDiv.value.addEventListener('mousemove', handleMouseMove);
	}
	return () => {
		if (fullscreenDiv.value) {
			fullscreenDiv.value.removeEventListener('mousemove', handleMouseMove);
		}
	};
});

// --------------------------------屏幕操作END-----------------------------------<(string | number)[]>----

let playIds = ref<string[]>([]);
const determineList = ref<boolean[]>([]);

// 跳转大屏
const toDashBoard = (): void => {
	document.body.requestFullscreen();
	router.push(
		`/monitoring-center/situation?inspection=${inspectionChecked.value}&playIds=${JSON.stringify(playIds.value)}`
	);
};

/**
 * 分屏幕按钮 */
const handleClickChangeScreen = async (params: number): Promise<void> => {
	try {
		// 关闭流
		if (params < currentConfig.value.screenType) {
			let closeVideoList: number[] = [];
			currentConfig.value.deviceIds.forEach((item, index) => {
				if (index > params - 1) {
					closeVideoList.push(item.areaOrDeviceId);
					videoError(item.id);
				}
			});
			realVideoApi.getClose(closeVideoList);
		}
		currentConfig.value.screenType = params;
		currentConfig.value.deviceIds = currentConfig.value.deviceIds.slice(
			0,
			params
		);
		playIds.value = playIds.value.slice(0, params);
		rememberParma();
	} catch (error) {
		console.log('error', error);
	}
};

// ----------------------------------webSocket----------------------------------------------

const { WebSocketStore } = appStore;
const { SocketState, ScoketSend } = WebSocketStore;
// websocket 智能巡检推送视频
const socketInspection = (obj: {
  data: {
    index: number;
    inspectionRedisVo: { id: string; determine: boolean };
  };
}) => {
	if (inspectionChecked.value) {
		let screenNum: number = currentConfig.value.screenType;

		if (obj.data.index - 1 < screenNum) {
			playIds.value[obj.data.index - 1] = obj.data.inspectionRedisVo.id;
			determineList.value[obj.data.index - 1] =
        obj.data.inspectionRedisVo.determine;
			expandedKeys.value = playIds.value;
			currentConfig.value.determineList = determineList.value;
			refTree.value.changeExpanded(playIds.value);
			// 重复不取消
			if (
				currentConfig.value.deviceIds.find(
					(item) => item?.id === obj.data.inspectionRedisVo.id
				)
			) {
				return;
			}
			// 从treeData的扁平数据中获取数据, 并对应 playIds 中 所在的index位置
			if (refTree.value && refTree.value.flatObj) {
				const newList: any[] = findNodeByIndex(
					refTree.value.flatObj,
					playIds.value
				);
				const viewCount = obj.data.index - 1;
				// 关闭上一次
				if (currentConfig.value.deviceIds[viewCount]) {
					closeVideo(
						currentConfig.value.deviceIds[viewCount].id,
						true,
						false,
						currentConfig.value.deviceIds[viewCount].areaOrDeviceId
					);
				}
				currentConfig.value.deviceIds[viewCount] = newList[viewCount];

				videoRender(newList[viewCount], viewCount);
			}
		}
	}
};

SocketState.ws.onmessage = async (info: { data: string }) => {
	try {
		if (route.path !== '/monitoring-center/real-video') {
			return;
		}
		let obj = JSON.parse(info.data);
		exceedAuthority(obj);
		switch (obj.message) {
			case 'ALARM_MESSAGE':
				alarmBarRef.value.getData(obj.data);
				break;

			case 'INSPECTION_MESSAGE':
				socketInspection(obj);
				break;

			case 'MONITOR_DEVICE_TREE':
				getTree();
				break;

			case 'SEND_CHECK_VIDEO_MESSAGE':
				realVideoApi.getCheck({
					ids: currentConfig.value.deviceIds.map((item) => item.areaOrDeviceId),
					inspection: inspectionChecked.value ? 0 : 1
				});
				break;

			default:
				break;
		}
	} catch (error) {
		console.log('error', error);
	}
};

// ----------------------------------webSocket END-------------------------------------------

// 空状态个数
const emptyNums = computed(
	() => currentConfig.value.screenType - currentConfig.value.deviceIds.length
);

// 页面布局
const cMonitorVideoStyle = computed(() => {
	let isShowAlarmList =
    LayoutStore.triggerScreen || !devicesTreeVisible.value
    	? '1fr 328px'
    	: '231px 1fr 328px';
	let obj = {
		gridTemplateColumns:
      LayoutStore.triggerScreen && !screenFull.value ? '1fr' : isShowAlarmList,
		padding: LayoutStore.triggerScreen ? '0' : '',
		gridColumnGap: LayoutStore.triggerScreen ? '0' : '6px'
	};
	return obj;
});

const cVideoCenterStyle = computed(() => {
	let obj = {
		gridTemplateRows: LayoutStore.triggerScreen
			? '1fr'
			: '40px minmax(8px, 1fr) 56px'
	};
	return obj;
});

// 获取页面记忆
const getRemember = async (): Promise<void> => {
	try {
		let res: TsRes = await realVideoApi.getRemember();
		if (res && res.data) {
			inspectionChecked.value = false;
			currentConfig.value.screenType = res.data.screenNums;
			expandedKeys.value = res.data.openIds;
			alarmChecked.value = res.data.changeStatus === 0 ? false : true;
			recognizeRegionSwitch.value = res.data.identifyArea === 0 ? true : false;

			if (refTree.value && refTree.value.flatObj) {
				currentConfig.value.deviceIds = findNodeByIndex(
					refTree.value.flatObj,
					res.data.playIds
				);
			}
			if (res.data.deviceIds.length) {
				getVideoList(res.data.deviceIds);
			}
			// currentConfig.value.deviceIds = findTreeData(res.data.playIds, treeData.value);
			currentConfig.value.deviceIds.forEach((item: TsDeviceIdsItem, index) => {
				videoRender(item, index);
			});
			await getAlarmList();
		}
	} catch (error) {
		console.log('error', error);
	}
};

// 智能巡检
const setTableData = async (): Promise<void> => {
	try {
		inspectionVisible.value = false;
		inspectionChecked.value = true;
		currentConfig.value.deviceIds.map((item: any) => {
			closeVideo(item.id, true, false, item.areaOrDeviceId);
		});
		currentConfig.value.deviceIds = [];
		await realVideoApi.startInspection();
	} catch (error) {
		console.log('error', error);
	}
};
// 跳转大屏
const skipSituation = async () => {
	let flag = sessionStorage.getItem('firstSkipRealVideo');
	if (flag === '0') {
		toDashBoard();
	}
	sessionStorage.setItem('firstSkipRealVideo', '1'); //重置登录首次跳转大屏
};

const closeModel = (): void => {
	inspectionVisible.value = false;
	inspectionChecked.value = false;
};

onMounted(async () => {
	ScoketSend({ webPage: 'realVideo', userId: token, stater: 0 });
	await getTree();
	await getRemember();
	await skipSituation();
	nextTick(() => {
		getPopupContainerEl.value = document.getElementById(
			'screen-button'
		) as HTMLElement;
	});
});

onUnmounted(() => {
	watchStop();
	watchEffectStop();
	ScoketSend({ webPage: 'realVideo', userId: token, stater: 1 });
	currentConfig.value.deviceIds.map((item: any) => {
		videoError(item.id);
	});
});
</script>

<style lang="less" scoped>
@import url("../../style.less");
</style>
